package com.chao.juc.pc;

/**
 * @author : Rookie
 * @description :
 * @date : 2022/1/17
 */
public class Pc {

    public static void main(String[] args) {

        Resource resource = new Resource();

        new Thread(() ->{
            for (int i = 0; i < 10; i++) {
                try {
                    resource.incrementOne();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();

        new Thread(() ->{
            for (int i = 0; i < 10; i++) {
                try {
                    resource.decrementOne();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();

        new Thread(() ->{
            for (int i = 0; i < 10; i++) {
                try {
                    resource.incrementOne();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"C").start();

        new Thread(() ->{
            for (int i = 0; i < 10; i++) {
                try {
                    resource.decrementOne();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"D").start();
    }
}

/**
 * 资源类
 */
class Resource{

    private int num = 0;

    public synchronized void incrementOne() throws InterruptedException {
        while (num != 0){
            //等待
            this.wait();
        }
        num ++;
        System.out.println(Thread.currentThread().getName() + "==>" +num);
        //通知其他线程
        this.notifyAll();
    }

    public synchronized void decrementOne() throws InterruptedException {
        while (num == 0){
            //等待
            this.wait();
        }
        num --;
        System.out.println(Thread.currentThread().getName() + "==>" +num);
        //通知
        this.notifyAll();
    }
}
